package com.example.jwtjava.common;

import cn.hutool.core.util.StrUtil;
import com.example.jwtjava.exception.ServiceException;
import com.example.jwtjava.util.JwtUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

/**
 * @Author 宋伟宁
 * @Date 2023/10/23
 * @Version 1.0
 **/
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.err.println("------------------------------");
           //获取头部
        String token = request.getHeader("token");
        System.out.println("服务器得到的token："+token);
        if(StrUtil.isBlank(token)){
             token = request.getParameter("token");

        }

        //如果存在token，则判断该token是否有效
        if(JwtUtils.checkToken(token)){
            System.out.println("token验证通过");
            return  true;
        }else{
            System.out.println("token未能验证通过");
            throw  new JwtException("token验证失败");
        }
    }
}
